<script setup lang="ts">
import { onMounted, ref } from 'vue';
// import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { fetchMarketDataList } from '@/service/api/market-data';
// import RateCurveDisplay from './modules/RateCurveDisplay.vue';
// import VolatilitySurfaceDisplay from './modules/VolatilitySurfaceDisplay.vue';
// import SpotPriceDisplay from './modules/SpotPriceDisplay.vue';
// import CurrencyPairConfigDisplay from './modules/CurrencyPairConfigDisplay.vue';
import { useRouterPush } from '@/hooks/common/router';
const { routerPushByKey } = useRouterPush();
// const route = useRoute();

// 响应式数据
const loading = ref(false);
const marketDataList = ref<any[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});
// const detailData = ref<any>(null);
// const detailLoading = ref(false);
// const renderKey = ref(0);

// 表格列定义
const columns: TableColumnsType = [
  {
    title: 'ID',
    dataIndex: 'marketId',
    key: 'id',
    width: 120,
    ellipsis: true
  },
  {
    title: '市场数据日期',
    dataIndex: 'horizonDate',
    key: 'horizonDate',
    width: 230
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 200,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
];

// 获取市场数据列表
async function fetchData() {
  try {
    loading.value = true;
    const response = (await fetchMarketDataList()).data;
    if (response && Array.isArray(response)) {
      marketDataList.value = response;
      pagination.value.total = response.length;
    } else {
      marketDataList.value = [];
      pagination.value.total = 0;
    }
  } catch (error) {
    console.log('获取市场数据失败:', error);
    message.error('获取市场数据失败，请稍后重试');
    marketDataList.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
};

// 查看详情
const viewDetail = (record: any) => {
  routerPushByKey('valuation_market-data-detail', {
    query: { id: record.marketId || record.id, view: 'detail' }
  });
};

// 当前请求的ID，用于防止重复请求
// const currentRequestId = ref<string | null>(null);

// 获取详情数据
// const fetchDetailData = async (id: string) => {
//   if (!id) {
//     console.log('详情ID为空，跳过数据获取');
//     return;
//   }

//   // 如果正在请求相同的ID，跳过
//   if (currentRequestId.value === id && detailLoading.value) {
//     console.log('正在请求相同ID，跳过重复请求:', id);
//     return;
//   }

//   console.log('开始获取详情数据，ID:', id);
//   currentRequestId.value = id;
//   detailLoading.value = true;

//   try {
//     const response = (await fetchMarketDataById(id)).data;
//     console.log('API返回数据:', response);

//     // 检查请求是否已过期（用户可能已切换到其他页面）
//     if (currentRequestId.value !== id) {
//       console.log('请求已过期，忽略结果');
//       return;
//     }

//     if (response) {
//       detailData.value = response;
//       console.log('详情数据设置成功:', detailData.value);
//       // 强制触发响应式更新
//       await nextTick();
//       renderKey.value++;
//       console.log('强制更新完成，renderKey:', renderKey.value);
//     } else {
//       detailData.value = null;
//       console.log('API返回数据为空');
//     }
//   } catch (error) {
//     console.error('获取详情数据失败:', error);
//     message.error('获取详情数据失败，请稍后重试');
//     detailData.value = null;
//   } finally {
//     if (currentRequestId.value === id) {
//       detailLoading.value = false;
//       currentRequestId.value = null;
//     }
//     console.log('详情数据加载完成，loading状态:', detailLoading.value);
//   }
// };

// 计算当前视图模式
// const currentView = computed(() => {
//   return route.query.view === 'detail' ? 'detail' : 'list';
// });

// 当前详情ID
// const detailId = computed(() => {
//   return route.query.id as string;
// });
// 监听路由变化
// watch(
//   () => route.query,
//   async (newQuery, oldQuery) => {
//     // 等待DOM更新完成
//     await nextTick();

//     if (currentView.value === 'list') {
//       // 清空详情数据
//       detailData.value = null;
//       fetchData();
//     } else if (currentView.value === 'detail' && detailId.value) {
//       fetchDetailData(detailId.value);
//     }
//   },
//   { immediate: true }
// );

// 检查对象是否为空
// const isEmptyObject = (obj: any) => {
//   return !obj || (typeof obj === 'object' && Object.keys(obj).length === 0);
// };

// 检查是否有有效数据
// const hasValidData = computed(() => {
//   if (!detailData.value) {
//     console.log('detailData为空');
//     return false;
//   }

//   const hasRateCurve = !isEmptyObject(detailData.value.quoteRateCurveMap);
//   const hasVolatilitySurface = !isEmptyObject(detailData.value.quoteVolatilitySurfaceMap);
//   const hasSpotPrice = !isEmptyObject(detailData.value.spotPriceMap);
//   const hasCurrencyConfig = !isEmptyObject(detailData.value.currencyPairConfig);

//   console.log('数据有效性检查:', {
//     hasRateCurve,
//     hasVolatilitySurface,
//     hasSpotPrice,
//     hasCurrencyConfig,
//     rateCurveData: detailData.value.quoteRateCurveMap,
//     volatilityData: detailData.value.quoteVolatilitySurfaceMap,
//     spotPriceData: detailData.value.spotPriceMap,
//     currencyConfigData: detailData.value.currencyPairConfig
//   });

//   return hasRateCurve || hasVolatilitySurface || hasSpotPrice || hasCurrencyConfig;
// });

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    INTEREST_RATE: 'blue',
    EXCHANGE_RATE: 'green',
    STOCK_PRICE: 'orange',
    COMMODITY_PRICE: 'purple',
    VOLATILITY: 'red',
    CREDIT_SPREAD: 'cyan'
  };
  return colorMap[type] || 'default';
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return dateStr;
  }
};

// 组件挂载时根据当前视图获取数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="market-data-container">
    <!-- 列表视图 -->
    <div>
      <ACard title="市场数据管理" :bordered="false">
        <template #extra>
          <ASpace>
            <AButton type="primary" :loading="loading" @click="fetchData">
              <template #icon>
                <ReloadOutlined />
              </template>
              刷新数据
            </AButton>
          </ASpace>
        </template>

        <ATable
          :columns="columns"
          :data-source="marketDataList"
          :loading="loading"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
          }"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <ASpace>
                <AButton type="link" @click="viewDetail(record)">查看详情</AButton>
              </ASpace>
            </template>
            <template v-else-if="column.key === 'marketDataType'">
              <ATag :color="getTypeColor(record.marketDataType)">
                {{ record.marketDataType }}
              </ATag>
            </template>
            <template v-else-if="column.key === 'value'">
              <span v-if="typeof record.value === 'number'">
                {{ record.value.toFixed(6) }}
              </span>
              <span v-else>{{ record.value }}</span>
            </template>
            <template v-else-if="column.key === 'lastUpdated'">
              <span v-if="record.lastUpdated">
                {{ formatDate(record.lastUpdated) }}
              </span>
              <span v-else>-</span>
            </template>
          </template>
        </ATable>
      </ACard>
    </div>

    <!-- 详情视图 -->
    <!--
 <div v-else-if="currentView === 'detail'" :key="renderKey">
      <Card :bordered="false">
        <template #title>
          <Space>
            <Button type="text" @click="backToList">
              <template #icon>
                <ArrowLeftOutlined />
              </template>
              返回列表
            </Button>
            <span>市场数据详情</span>
          </Space>
        </template>

        <div v-if="detailLoading" style="text-align: center; padding: 50px">
          <Spin size="large" />
        </div>
        <div v-else-if="detailData">
          <Descriptions title="基本信息" :column="3" bordered style="margin-bottom: 24px">
            <DescriptionsItem label="数据类型">
              <Tag :color="getTypeColor(detailData.marketDataType)">
                {{ detailData.marketDataType }}
              </Tag>
            </DescriptionsItem>
            <DescriptionsItem label="最后更新时间">
              {{ detailData.lastUpdated ? formatDate(detailData.lastUpdated) : '-' }}
            </DescriptionsItem>
            <DescriptionsItem label="数据来源">
              {{ detailData.source || '-' }}
            </DescriptionsItem>
          </Descriptions>

          <div>
            <Tabs v-if="hasValidData" default-active-key="rateCurve" type="card">
              <TabPane v-if="!isEmptyObject(detailData.quoteRateCurveMap)" key="rateCurve" tab="收益率曲线">
                <RateCurveDisplay :rate-curve-map="detailData.quoteRateCurveMap" />
              </TabPane>
              <TabPane
                v-if="!isEmptyObject(detailData.quoteVolatilitySurfaceMap)"
                key="volatilitySurface"
                tab="波动率曲面"
              >
                <VolatilitySurfaceDisplay :volatility-surface-map="detailData.quoteVolatilitySurfaceMap" />
              </TabPane>
              <TabPane v-if="!isEmptyObject(detailData.spotPriceMap)" key="spotPrice" tab="即期汇率">
                <SpotPriceDisplay :spot-price-data="detailData.spotPriceMap" />
              </TabPane>
              <TabPane v-if="!isEmptyObject(detailData.currencyPairConfig)" key="currencyConfig" tab="货币对配置">
                <CurrencyPairConfigDisplay :config-data="detailData.currencyPairConfig" />
              </TabPane>
            </Tabs>
            <div v-else class="no-data-message">
              <Empty description="暂无市场数据或数据格式不正确" />
              <p style="margin-top: 16px; color: #666; text-align: center">
                数据结构: {{ JSON.stringify(detailData, null, 2) }}
              </p>
            </div>
          </div>
        </div>
        <div v-else style="text-align: center; padding: 50px">
          <Empty description="暂无数据" />
        </div>
      </Card>
    </div>
-->
  </div>
</template>

<style scoped>
.market-data-container {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.ant-btn-link) {
  padding: 0;
  height: auto;
}
</style>
